<template>
  <main class="main" ref="mainRef">
    <div class="side-bar">
      <p
        class="title"
        v-if="props.active === 'grade' || props.active === 'class'"
      >
        {{ getGradeOrClass }} 学情报告
      </p>
      <ul class="student-list" v-if="props.active === 'student'">
        <li
          v-for="(item, index) in studentList"
          :key="index"
          :class="{ active: item.id === currentStudent.id }"
          @click="changeCurrentStudent(item)"
        >
          {{ item.name }}
        </li>
      </ul>
      <a-anchor
        v-else
        :affix="false"
        :offsetTop="24"
        :getCurrentAnchor="() => currentAnchor"
        :getContainer="() => mainRef?.parentNode"
      >
        <a-anchor-link
          :class="{ 'active-outer': activeIndex === index }"
          v-for="(item1, index) in getTabs"
          :key="item1.name"
          :title="item1.desc"
          :href="`#${item1.children[0].name}`"
          @click.self="changeActive(index)"
        >
          <a-anchor-link
            class="inner"
            v-for="item2 in item1.children"
            :class="{ 'active-inner': currentAnchor === `#${item2.name}` }"
            :key="item2.name"
            :title="item2.desc"
            :href="`#${item2.name}`"
            @click="changeAnchor(item2.name, index, item1.children)"
          ></a-anchor-link>
        </a-anchor-link>
      </a-anchor>
    </div>
    <div class="content" ref="contentRef">
      <template v-if="props.active === 'grade'">
        <grade-summary id="summary"></grade-summary>
        <comprehensive-comparison id="comparison"></comprehensive-comparison>
        <knowledge-point
          id="keyPoint"
          :activeTab="props.active"
        ></knowledge-point>
        <common-mistakes
          id="commonMistakes"
          :activeTab="props.active"
        ></common-mistakes>
        <teaching-quality id="teachingQuality"></teaching-quality>
        <grade-distribution
          id="gradeDistribution"
          :activeTab="props.active"
        ></grade-distribution>
      </template>
      <template v-else-if="props.active === 'class'">
        <class-summary id="summary"></class-summary>
        <grade-trends id="resultTrends"></grade-trends>
        <knowledge-point
          id="keyPoint"
          :activeTab="props.active"
        ></knowledge-point>
        <common-mistakes
          id="commonMistakes"
          :activeTab="props.active"
        ></common-mistakes>
        <core-competencies id="coreCompetencies"></core-competencies>
        <class-teaching-quality id="teachingQuality"></class-teaching-quality>
        <grade-distribution
          id="gradeDistribution"
          :activeTab="props.active"
        ></grade-distribution>
        <student-performance id="studentPerformance"></student-performance>
      </template>
      <template v-else-if="props.active === 'student'">
        <student-page
          :studentId="currentStudent.id"
          :studentName="currentStudent.name"
        ></student-page
      ></template>
    </div>
  </main>
</template>
<script setup>
import { GRADE_TABS, CLASS_TABS } from '../constant'
import { ref, computed, reactive, watch } from 'vue'
import GradeSummary from '../grade/GradeSummary.vue'
import CommonMistakes from '../grade/CommonMistakes.vue'
import KnowledgePoint from '../grade/KnowledgePoint.vue'
import TeachingQuality from '../grade/TeachingQuality.vue'
import ComprehensiveComparison from '../grade/ComprehensiveComparison.vue'
import GradeDistribution from '../grade/GradeDistribution.vue'
import GradeTrends from '../class/GradeTrends.vue'
import ClassSummary from '../class/ClassSummary.vue'
import ClassTeachingQuality from '../class/ClassTeachingQuality.vue'
import CoreCompetencies from '../class/CoreCompetencies.vue'
import StudentPerformance from '../class/StudentPerformance.vue'
import StudentPage from '../students/index.vue'
import { getStudentsList } from '@/apis/situation-report/index'
import { useSituationReport } from '@/stores/situation-report'
import { useAuthStore } from '@/stores/auth-store.js'
import { onMounted, onBeforeUnmount } from 'vue'
import $bus from '@/utils/tools/bus'
const userStore = useAuthStore()
const situationReport = useSituationReport()
const props = defineProps({
  active: {
    type: String,
    default: 'grade'
  }
})
const contentRef = ref(null)
const mainRef = ref()
const currentAnchor = ref('#summary')
const currentStudent = reactive({
  id: '',
  name: ''
})

const changeCurrentStudent = item => {
  currentStudent.id = item.id
  currentStudent.name = item.name
}

const changeAnchor = (name, index, list) => {
  if (index === getTabs.value.length - 1 && list.at(-1).key === name) {
    setTimeout(() => {
      currentAnchor.value = `#${list.at(-1).key}`
      activeIndex.value = index
    }, 350)
  }
  currentAnchor.value = `#${name}`
  activeIndex.value = index
}

const getGradeOrClass = computed(() => {
  if (props.active === 'grade') {
    const flag = situationReport.search.grade_id
    const list = userStore?.allGradeList || []
    const res = list.find(item => item.value === Number(flag))?.label || []
    return res
  } else if (props.active === 'class') {
    const flag = situationReport.search.class_id
    const list = userStore?.allClassList || []
    const res =
      list.find(item => item.F_class_id === flag)?.['F_class_name'] || ''
    return res
  }
  return ''
})

const activeIndex = ref(0)
const studentList = ref([])

// 学生学情获取学生列表
const getStudents = async () => {
  const { data } = await getStudentsList({
    class_id: situationReport.search.class_id
  })
  studentList.value = data?.list || []
}

const changeActive = index => {
  activeIndex.value = index
  currentAnchor.value = `#${getTabs.value[index].children[0].name}`
}

// 左侧导航栏
const getTabs = computed(() => {
  if (props.active === 'grade') {
    return GRADE_TABS
  } else if (props.active === 'class') {
    return CLASS_TABS
  }
  return []
})

watch(
  () => situationReport.search.class_id,
  async val => {
    if ((props.active === 'student' || props.active === 'class') && val) {
      await getStudents()
      currentStudent.id = studentList.value[0]?.id
      currentStudent.name = studentList.value[0]?.name
    }
  }
)

onMounted(() => {
  $bus.on('change-tab', async val => {
    await getStudents()
    if (val.from === 'tab') {
      currentStudent.id = studentList.value[0]?.id
      currentStudent.name = studentList.value[0]?.name
    } else {
      setTimeout(() => {
        if (val?.id) {
          currentStudent.id = val?.id || ''
          currentStudent.name = val?.name || ''
        }
      }, 200)
    }
  })
})

onBeforeUnmount(() => {
  $bus.off('change-tab')
})

defineExpose({
  activeIndex,
  getTabs,
  currentAnchor
})
</script>
<style lang="less" scoped>
@import '../style.less';

.main {
  display: flex;
  gap: @gap;

  .side-bar {
    width: 360px;
    background: #fff;
    padding: @gap;
    position: sticky;
    top: 0;
    border-radius: @big-radius;
    height: fit-content;
    overflow: scroll;

    .title {
      font-size: 20px;
      font-weight: 700;
      margin-bottom: 16px;
    }

    :deep(.ant-anchor-wrapper) {
      .ant-anchor-ink {
        display: none;
        padding: 0;
      }

      * {
        color: @minor-font-color;
      }

      .ant-anchor-link-title {
        &:hover {
          background: rgb(77 136 255 / 0.15);
        }
      }

      .ant-anchor-link {
        padding: 0;

        * {
          font-size: @base-size;
        }

        & > :first-child {
          padding: 0 16px;
        }

        &-title {
          border-radius: @small-radius;
          width: 100%;
          display: inline-block;
          height: 56px;
          line-height: 56px;
          margin: 0;
        }
      }

      .active-outer {
        & > :first-child {
          background: #f3f5fb;
          color: #4d88ff;
          font-weight: 800;
        }
      }

      .inner {
        &.active-inner {
          .ant-anchor-link-title {
            color: #4d88ff;
            font-weight: 500;
          }
        }

        .ant-anchor-link-title {
          padding: 0 32px;
        }
      }
    }

    .student-list {
      li {
        height: 56px;
        list-style-type: none;
        display: flex;
        align-items: center;
        border-radius: @small-radius;
        padding: 0 16px;

        &:hover {
          background: rgb(77 136 255 / 0.15);
        }
      }

      .active {
        border-radius: @small-radius;
        background: #f3f5fb;

        * {
          color: #4d88ff;
          font-weight: 500;
        }
      }
    }
  }

  .content {
    border-radius: @big-radius;
    overflow: scroll;
    display: flex;
    flex-direction: column;
    gap: @gap;
    flex: 1;

    &::-webkit-scrollbar {
      width: 0 !important;
    }
  }
}
</style>
